//
//  RegisterVC.m
//  UHealth
//
//  Created by gjtxz on 15/1/16.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "RegisterVC.h"
#import "iToast.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "NavView.h"
#import "DBManage.h"

@interface RegisterVC ()<ViewPagerDataSource, ViewPagerDelegate>

@property (nonatomic,strong) UITextField    *fieldUser;
@property (nonatomic,strong) UITextField    *fieldPassword;
@property (nonatomic,strong) UITextField    *fieldCode;

@property (nonatomic)       BOOL            isNormal;

@property (nonatomic,strong) NSTimer        *countTimer;
@property (nonatomic)        NSInteger      count;

@end

@implementation RegisterVC

-(id)init
{
    self = [super init];
    if (self) {
        self.view.backgroundColor = kBacColor;
    }
    return self;
}

- (void)viewDidLoad {
    
    // Do any additional setup after loading the view.
    
    self.dataSource = self;
    self.delegate = self;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [super viewDidLoad];
    
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"register") andVC:self];
    [self.view addSubview:nav];
    
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidenKeyboard)];
    gesture.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:gesture];
    
    return;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)BtnCount:(NSTimer *)timer
{
    _count --;
    UIButton *btn = (UIButton *)timer.userInfo;
    if (_count <= 0) {
        btn.enabled = YES;
        [_countTimer invalidate];
        _countTimer = nil;
        [btn setTitle:kLocal(@"getcode") forState:UIControlStateNormal];
    }else{
        [btn setTitle:[NSString stringWithFormat:@"%d%@",(int)_count,kLocal(@"sec")] forState:UIControlStateNormal];
    }

}

- (void)BtnClick:(UIButton *)btn
{
    NSString *user = _fieldUser.text;
    NSString *password = _fieldPassword.text;
    NSString *code = _fieldCode.text;
    
    if ((!user.length || (password.length<6 && password.length >12)|| (!code.length && !_isNormal)) && btn.tag <=1) {
        [[iToast makeText:kLocal(@"please_input_info")] show];
        return;
    }else if(btn.tag  == 10){
        if (!user.length) {
            [[iToast makeText:kLocal(@"please_input_phone")] show];
            return;
        }
        btn.enabled = NO;
        _count = 60;
        [btn setTitle:[NSString stringWithFormat:@"%d%@",(int)_count,kLocal(@"sec")] forState:UIControlStateNormal];
        _countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(BtnCount:) userInfo:btn repeats:YES];
        
    }
    [self.view endEditing:YES];
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")] show];
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/login.jsp",kBaseUrl];
    
    NSDictionary *parameters;
    if (_isNormal) {//普通注册
        parameters = @{@"action": @"reg",
                       @"username":user,
                       @"password":password,
                       @"jpush_registrationid":kJiGuang,
                       @"umeng_device_token" :kUMengDeviceToken,
                       @"mobile_type":@"2",
                       @"mobile_lng":@"",
                       @"mobile_lat":@"",
                       @"mem_name":_user.name,
                       @"mem_sex":[NSString stringWithFormat:@"%d",_user.sex],
                       @"mem_birth":_user.birthDate,
                       @"men_shenggao":[NSString stringWithFormat:@"%03.0f",_user.height],
                       @"men_tizhong":[NSString stringWithFormat:@"%03.0f",_user.weight],
                       @"filenum":[NSString stringWithFormat:@"%d",_myImg != nil]};
    }else{
        if (btn.tag == 10) {//获取验证码
            parameters = @{@"action": @"getverify",
                           @"mobile":user,
                           @"opt":@"1"};
        }else{//手机注册
            
            parameters = @{@"action": @"mobilereg",
                           @"mobile":user,
                           @"password":password,
                           @"verify":code,
                           @"jpush_registrationid":kJiGuang,
                           @"mobile_type":@"2",
                           @"mobile_lng":@"",
                           @"mobile_lat":@"",
                           @"mem_name":_user.name,
                           @"mem_sex":[NSString stringWithFormat:@"%d",_user.sex],
                           @"mem_birth":_user.birthDate,
                           @"men_shenggao":[NSString stringWithFormat:@"%.0f",_user.height],
                           @"men_tizhong":[NSString stringWithFormat:@"%.0f",_user.weight],
                           @"filenum":[NSString stringWithFormat:@"%d",_myImg != nil]};
        }
    }
    
    [manager POST:postStr parameters:parameters constructingBodyWithBlock:^(id formData){
        if (_myImg) {
            [formData appendPartWithFileData:UIImagePNGRepresentation(_myImg) name:@"img0" fileName:@"img0.png" mimeType:@"image/png"];
        }
        //        [formData appendPartWithFileURL:[NSURL fileURLWithPath:kPostImgFilePath] name:@"img0" error:nil];
        
    }success:^(AFHTTPRequestOperation *operation, id responseObject) {
        kDebug(@"Success: %@", operation.responseString);
        //        {"type":true,"userid":22120242,"msg":"注册成功"}
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        if(type){//注册成功
            if ( btn.tag == 10) {//获取验证码
                
            }else{
                NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
                int userid = [[responseObject objectForKey:@"userid"] intValue];
                [def setInteger:userid forKey:kNetUserID];//服务ID
                
                [def setObject:user forKey:kNetUserName];//账户名
                if (!_isNormal) {
                    [def setObject:user forKey:kNetUserPhone];//手机
                }else{
                    [def setObject:@"" forKey:kNetUserPhone];//手机为空
                }
                [def synchronize];
                
                //主账号 插入或者更新
                [[DBManage sharedManager]insertData:_user andTable:kUserTable];
                
                //家庭成员
                AppDelegate *delegate = [UIApplication sharedApplication].delegate;
                [delegate changRootVCToMain];
                //                _user.headImg = responseObject[@"mem_headpic"];
                //                NSString *setStr = [NSString stringWithFormat:@"%@ = '%@'",kUserHeadImg,_user.headImg];
                //                NSString *conStr = [NSString stringWithFormat:@"%@ = '%d' ",kUserID,_user.userID];
                //                [[DBManage sharedManager] updateData:setStr andTable:kUserTable andConditions:conStr];
                
            }
        }else{
            
        }
        //如果手机已经注册，显示帐号已经存在，未注册的显示发送成功
        //type = 1发送成功 0表示存在
        [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
        
    }];
    
}

-(void)hidenKeyboard
{
    [_fieldUser resignFirstResponder];
    [_fieldPassword resignFirstResponder];
    [_fieldCode resignFirstResponder];
}


#pragma mark -ViewPagerDataSource
- (NSUInteger)numberOfTabsForViewPager:(ViewPagerController *)viewPager
{
    return 2;
}
- (UIView *)viewPager:(ViewPagerController *)viewPager viewForTabAtIndex:(NSUInteger)index
{
    UILabel *label = [[UILabel alloc]init];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:13.0];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor blackColor];
    [label sizeToFit];
    label.frame = CGRectMake(0, kNavHeight, WIDTH/2, 44);
    if (index == 0) {
        label.text = kLocal(@"phonereg");
    }else{
        label.text = kLocal(@"namereg");
    }
    
    return label;
}

//- (UIViewController *)viewPager:(ViewPagerController *)viewPager contentViewControllerForTabAtIndex:(NSUInteger)index {
//    
//    UIViewController *cvc = [[UIViewController alloc]init];
//    cvc.view = view;
//    return cvc;
//}

- (UIView *)viewPager:(ViewPagerController *)viewPager contentViewForTabAtIndex:(NSUInteger)index
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, kNavHeight+44, WIDTH, HEIGHT - kNavHeight - 44)];
    
    UILabel *hit1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 5 , WIDTH-40, 20)];
    hit1.text = kLocal(@"hit2");
    hit1.font = [UIFont systemFontOfSize:12];
    [view addSubview:hit1];
    
    NSArray *imgArr = @[@"user",@"password",@"code"];
    for (int i = 0; i < 3; i++) {
        if (index == 1 && i == 2) {
            break;
        }
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(23, 33+i*30, 25, 25)];
        img.image = [UIImage imageNamed:imgArr[i]];
        [view addSubview:img];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, 60+ i*30, WIDTH - 40, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        [view addSubview:lineView];
    }
    
    _fieldUser = [[UITextField alloc]initWithFrame:CGRectMake(60, 33, WIDTH-80, 30)];
    _fieldUser.font = [UIFont systemFontOfSize:13.0];
    _fieldUser.clearButtonMode = UITextFieldViewModeWhileEditing;
    if (index == 0) {
        _fieldUser.placeholder = kLocal(@"phone");
        _fieldUser.keyboardType = UIKeyboardTypeNumberPad;
    }else{
        _fieldUser.placeholder = kLocal(@"user");
        _fieldUser.keyboardType = UIKeyboardTypeASCIICapable;
    }
    
    [view addSubview:_fieldUser];
    
    _fieldPassword = [[UITextField alloc]initWithFrame:CGRectMake(60, 63, WIDTH-80, 30)];
    _fieldPassword.font = [UIFont systemFontOfSize:13.0];
    _fieldPassword.placeholder = kLocal(@"password");
    _fieldPassword.secureTextEntry = YES; //密码
    _fieldPassword.keyboardType = UIKeyboardTypeASCIICapable;
    _fieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view addSubview:_fieldPassword];
    
    if (index == 0) {
        _fieldCode = [[UITextField alloc]initWithFrame:CGRectMake(60, 93, 220 - 65, 30)];
        _fieldCode.font = [UIFont systemFontOfSize:13.0];
        _fieldCode.placeholder = kLocal(@"code");
        _fieldCode.clearButtonMode = UITextFieldViewModeWhileEditing;
        _fieldCode.keyboardType = UIKeyboardTypeASCIICapable;
        [view addSubview:_fieldCode];
        
        UIButton *codeBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        codeBtn.frame = CGRectMake(220, 93, WIDTH- 220-20, 25);
        [codeBtn setTitle:kLocal(@"getcode") forState:UIControlStateNormal];
        [codeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [codeBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [codeBtn.layer setMasksToBounds:YES];
        [codeBtn.layer setCornerRadius:5.0];//设置矩形是个圆角半径
        codeBtn.backgroundColor = kBlueColor;
        codeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        codeBtn.tag  = 10;
        [view addSubview:codeBtn];
    }
    
    UIButton *regBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    regBtn.frame = CGRectMake(40, 150, view.frame.size.width - 80, 40);
    [regBtn setTitle:kLocal(@"register") forState:UIControlStateNormal];
    [regBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [regBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [regBtn.layer setMasksToBounds:YES];
    [regBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    regBtn.backgroundColor = kBlueColor;
    regBtn.tag  = index;
    [view addSubview:regBtn];
    
    return view;
}


#pragma mark -ViewPagerDelegate
- (void)viewPager:(ViewPagerController *)viewPager didChangeTabToIndex:(NSUInteger)index
{
    _isNormal = index;
}

- (CGFloat)viewPager:(ViewPagerController *)viewPager valueForOption:(ViewPagerOption)option withDefault:(CGFloat)value {
    
    switch (option) {
        case ViewPagerOptionStartFromSecondTab:
            return 0.0;
            break;
        case ViewPagerOptionCenterCurrentTab:
            return 1.0;
            break;
        case ViewPagerOptionTabLocation:
            return 1.0;
            break;
        case ViewPagerOptionTabHeight:
            return 40.0;
            break;
        case ViewPagerOptionTabWidth:
            return WIDTH/2;
            break;
            break;
        default:
            break;
    }
    
    return value;
}
- (UIColor *)viewPager:(ViewPagerController *)viewPager colorForComponent:(ViewPagerComponent)component withDefault:(UIColor *)color {
    
    switch (component) {
        case ViewPagerIndicator:
            return [kBlueColor colorWithAlphaComponent:0.64];
            break;
        default:
            break;
    }
    
    return color;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
